package com.doge.calcalbum

import android.app.Application
import android.os.Process
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.doge.calcalbum.core.AppLifecycleObserver
import com.doge.calcalbum.utils.OAIDUtils
import com.doge.calcalbum.utils.appChannel
import com.doge.calcalbum.utils.log
import com.hjq.permissions.XXPermissions
import com.tendcloud.tenddata.TCAgent

class App : Application(), ViewModelStoreOwner {
    private val appViewModelStore by lazy { ViewModelStore() }
    private val appViewModelFactory by lazy {
        ViewModelProvider.AndroidViewModelFactory.getInstance(
            this
        )
    }

    override fun onCreate() {
        context = this
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleObserver())
        XXPermissions.setScopedStorage(true)

        Thread {
            Process.setThreadPriority(Process.myTid(), Process.THREAD_PRIORITY_BACKGROUND)
            OAIDUtils.init()
            log("App onCreate oaId ${OAIDUtils.id}") // init oaid
            TCAgent.init(this, getString(R.string.td_app_id), appChannel)  // 110ms
            TCAgent.setReportUncaughtExceptions(true)  // 0ms
        }.start()
    }

    fun getAppViewModelProvider() = ViewModelProvider(this, appViewModelFactory)
    override fun getViewModelStore() = appViewModelStore
    fun getViewModelFactory() = appViewModelFactory

    companion object {
        lateinit var context: Application
    }
}